package com.hoshiibuy.sys.permission.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiibuy.common.aop.Logable;
import com.hoshiibuy.common.rpc.Response;
import com.hoshiibuy.sys.permission.dao.SysPermissionesMapper;
import com.hoshiibuy.sys.permission.dao.SysRolePermissionesMapper;
import com.hoshiibuy.sys.permission.dao.SysRolesMapper;
import com.hoshiibuy.sys.permission.entity.SysPermissiones;
import com.hoshiibuy.sys.permission.entity.SysRolePermissiones;
import com.hoshiibuy.sys.permission.entity.SysRoles;
import com.hoshiibuy.sys.permission.entity.param.RObject;
import com.hoshiibuy.sys.permission.feign.IdGeneratorRemote;
import com.hoshiibuy.sys.permission.feign.Neo4jRemote;
import com.hoshiibuy.sys.permission.service.ISysRolesService;

/**
 * <p>
 * 角色 服务实现类
 * </p>
 * TODO 添加事务，缓存,异常等处理
 * 
 * @author Mr.Wu
 * @since 2019-04-19
 */
@Service
public class SysRolesServiceImpl extends ServiceImpl<SysRolesMapper, SysRoles> implements ISysRolesService {

	@Autowired
	private SysRolePermissionesMapper sysRolePermissionesMapper;

	@Autowired
	private SysPermissionesMapper sysPermissionesMapper;

	@Autowired
	private SysRolesMapper sysRolesMapper;

	@Autowired
	private Neo4jRemote neo4jRemote;

	@Autowired
	private IdGeneratorRemote idGeneratorRemote;

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysRole", "sysRolePermissiones" }, allEntries = true)
	@Logable(authName = "权限相关-角色信息管理-新增角色信息")
	public Response addRole(SysRoles param) {
		param.setAddTime(LocalDateTime.now());
		param.setVersion(1);
		// 获取全局id
		String uuid = idGeneratorRemote.getId();
		if (StringUtils.isBlank(uuid)) {
			throw new ServiceException("id服务失败");
		}
		param.setId(Long.valueOf(uuid));
		// 插入角色表
		int count = sysRolesMapper.insert(param);
		if (count <= 0) {
			throw new ServiceException("新增失败");
		}
		// TODO Auto-generated method stub
		List<String> permissionIdList = param.getPermissionIdList();
		QueryWrapper<SysPermissiones> queryWrapper = new QueryWrapper<SysPermissiones>();
		queryWrapper.eq("status", "1");
		queryWrapper.in("id", permissionIdList);
		count = sysPermissionesMapper.selectCount(queryWrapper);
		if (count != permissionIdList.size()) {
			// 根据id列表查询到的可用权限不匹配，返回错误
			// return Response.failed("权限数量不匹配，请刷新重试");
			throw new ServiceException("可用权限数量不匹配，请刷新重试");
		}
		// 批量插入关联表
		for (String permissionId : permissionIdList) {
			SysRolePermissiones entity = new SysRolePermissiones();
			// 关联表使用本地ID生成
			entity.setId(IdWorker.getId());
			entity.setRoleId(param.getId());
			entity.setPermissionId(Long.valueOf(permissionId));
			count = sysRolePermissionesMapper.insert(entity);
		}

		// 插入neo4j节点
		RObject neo4jParam = new RObject();
		// 角色所属平台名称
		// TODO 根据关联ID获取平台名称
		// 测试写固定
		neo4jParam.setLabel("好获在一起");
		neo4jParam.setUuid(uuid);
		neo4jParam.addProperty("uuid", uuid);
		neo4jParam.addProperty("name", param.getName());
		Response result = neo4jRemote.addRole(neo4jParam);
		if (result != null && !result.isSuccess()) {
			throw new ServiceException("neo4j服务失败," + result.getMsg());
		} else if (result == null) {
			throw new ServiceException("neo4j服务失败");
		}
		return Response.success("新增成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysRole", "sysRolePermissiones" }, allEntries = true)
	@Logable(authName = "权限相关-角色信息管理-修改角色信息")
	public Response updateRole(SysRoles param) {
		// 更新角色数据
		int count = sysRolesMapper.updateById(param);
		if (count == 0) {
			// return Response.failed("修改失败");
			throw new ServiceException("修改失败");
		}

		List<String> permissionIdList = param.getPermissionIdList();
		if (permissionIdList != null) {
			// 更新关联数据
			// 删除关联信息
			SysRolePermissiones queryParam = new SysRolePermissiones();
			queryParam.setRoleId(param.getId());
			QueryWrapper<SysRolePermissiones> queryWrapper = new QueryWrapper<SysRolePermissiones>(queryParam);
			sysRolePermissionesMapper.delete(queryWrapper);
			// 添加新的关联信息

			QueryWrapper<SysPermissiones> queryWrapper_per = new QueryWrapper<SysPermissiones>();
			queryWrapper_per.eq("status", "1");
			queryWrapper_per.in("id", permissionIdList);
			count = sysPermissionesMapper.selectCount(queryWrapper_per);
			if (count != permissionIdList.size()) {
				// 根据id列表查询到的可用权限不匹配，返回错误
				throw new ServiceException("可用权限数量不匹配，请刷新重试");
			}
			// 批量插入关联表
			for (String permissionId : permissionIdList) {
				SysRolePermissiones entity = new SysRolePermissiones();
				entity.setId(IdWorker.getId());
				entity.setRoleId(param.getId());
				entity.setPermissionId(Long.valueOf(permissionId));
				count = sysRolePermissionesMapper.insert(entity);
			}
		}

		// TODO 判断角色上级是否改变,如果改变了修改neo4j节点

		return Response.success("修改成功");
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	@CacheEvict(cacheNames = { "sysRole", "sysRolePermissiones" }, allEntries = true)
	@Logable(authName = "权限相关-角色信息管理-删除角色信息")
	public Response deleteRole(String id) {

		// 删除关联信息
		SysRolePermissiones queryParam = new SysRolePermissiones();
		queryParam.setRoleId(Long.valueOf(id));
		QueryWrapper<SysRolePermissiones> queryWrapper = new QueryWrapper<SysRolePermissiones>(queryParam);
		sysRolePermissionesMapper.delete(queryWrapper);

		// 删除角色信息
		int count = sysRolesMapper.deleteById(id);
		if (count == 0) {
			throw new ServiceException("删除失败");
		}
		// 删除neo4j节点

		return Response.success("删除成功");
	}

	@Override
	@Cacheable(cacheNames = "sysRole", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
	@Logable(authName = "权限相关-角色信息管理-查询角色信息详情")
	public Response getRoleDetail(String id) {
		SysRoles sysRoles = sysRolesMapper.selectById(id);
		QueryWrapper<SysRolePermissiones> queryWrapper = new QueryWrapper<SysRolePermissiones>();
		queryWrapper.eq("role_id", id);
		List<SysRolePermissiones> list = sysRolePermissionesMapper.selectList(queryWrapper);
		List<String> permissionIdList = new ArrayList<String>();
		for (SysRolePermissiones sysRolePermissiones : list) {
			permissionIdList.add(sysRolePermissiones.getId().toString());
		}
		sysRoles.setPermissionIdList(permissionIdList);
		if (sysRoles == null) {
			return Response.failed("数据不存在");
		} else {
			return Response.data(sysRoles);
		}
	}

	@Override
	@Cacheable(cacheNames = "sysRole", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5(Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
	@Logable(authName = "权限相关-角色信息管理-查询角色信息列表")
	public Response getRoleList(Wrapper<SysRoles> queryWrapper) {
		return Response.data(sysRolesMapper.selectList(queryWrapper));
	}

	@Override
	@Cacheable(cacheNames = "sysRole", key = "T(com.hoshiibuy.common.utils.DigestUtils).md5('Page(current=' + #page.getCurrent() + ', size=' + #page.getSize() + '), Wrapper(SqlSelect=' + #queryWrapper.getSqlSelect() + ', SqlSegment=' + #queryWrapper.getSqlSegment() + ')')")
	@Logable(authName = "权限相关-角色信息管理-分页查询角色信息")
	public Response getPage(IPage<SysRoles> page, QueryWrapper<SysRoles> queryWrapper) {
		return Response.data(sysRolesMapper.selectPage(page, queryWrapper));
	}

}
